

import 'dart:convert';
import 'dart:io';

import 'package:dolqun_movies/Entities/MovieDetailsResult.dart';
import 'package:dolqun_movies/StateManagement/ModelProvider.dart';
import 'package:video_cache_manager/CacheManager.dart';
import 'package:path_provider/path_provider.dart' as PathProvider;

class CacheManagerModel extends Model {
  final HlsCacheManager cacheManager;
  _VisitHistoryManager _visitHistoryManager;

  CacheManagerModel({this.cacheManager}) {
    this.cacheManager.initialize().then((value) => print("Cache manager initialize success."));
    _visitHistoryManager = _VisitHistoryManager(fileName: "histories.json");
    _visitHistoryManager.initialize();
  }
}

class _VisitHistoryManager {
  File file;
  String _fileName;
  List<MovieDetails> movies = [];
  _VisitHistoryManager({String fileName}) {
    this._fileName = fileName;
  }

  Future<bool> initialize()async {
    var dir = await PathProvider.getApplicationDocumentsDirectory();
    file = File(dir.path + "/" + _fileName);
    if (!await file.exists()) {
      await file.create();
      await flush();
    }
    await load();
    return true;
  }
  Future<void> load() async {
    var jsonString = await file.readAsString();
    if (jsonString.isEmpty) jsonString = "[]";
    this.movies = (json.decode(jsonString) as List<dynamic>).map((e) => MovieDetails.fromJson(e)).toList();
  }
  Future<void> flush() async {
    var jsonString = json.encode(this.movies.map((e) => e.toJson()));
    await file.writeAsString(jsonString);
  }
}